/*
 * SecureHash.cpp
 *
 *  Created on: Sep 15, 2011
 *      Author: Gherman Alin
 */

#include "SecureHash.h"
#include <openssl/evp.h>

namespace Crypto {

const char* SecureHash::SHA256 = "sha256";
const char* SecureHash::SHA512 = "sha512";

SecureHash::SecureHash() {
}

unsigned int SecureHash::hash(const char *mode,
		const char* dataToHash, size_t dataSize,
		unsigned char* outHashed) {
	EVP_MD_CTX mdctx;
	unsigned int md_len;
	const EVP_MD *md = EVP_get_digestbyname(mode);

	EVP_MD_CTX_init(&mdctx);
	EVP_DigestInit_ex(&mdctx, md, NULL);
	EVP_DigestUpdate(&mdctx, dataToHash, dataSize);
	EVP_DigestFinal_ex(&mdctx, outHashed, &md_len);
	EVP_MD_CTX_cleanup(&mdctx);
	return md_len;
}

unsigned int SecureHash::hash(const char *mode, const std::string& data,
		std::string& outHashed) {
	unsigned char md_out[EVP_MAX_MD_SIZE];
	unsigned int md_len = hash(mode, data.data(), data.length(), md_out);
	outHashed.assign((char*) md_out, md_len);
	return md_len;
}

unsigned int SecureHash::hash256(const std::string& data, std::string& out) {
	return hash(SHA256, data, out);
}

unsigned int SecureHash::hash512(const std::string& data, std::string& out) {
	return hash(SHA512, data, out);
}

unsigned int SecureHash::hash256(const char* data, size_t size, unsigned char* out) {
	return hash(SHA256, data, size, out);
}

unsigned int SecureHash::hash512(const char* data, size_t size, unsigned char* out) {
	return hash(SHA512, data, size, out);
}

}
